package com.tongtech.system.service.impl;

import com.tongtech.common.core.constant.UserConstants;
import com.tongtech.common.core.exception.ServiceException;
import com.tongtech.common.core.text.Convert;
import com.tongtech.common.core.utils.SpringUtils;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.common.datascope.annotation.DataScope;
import com.tongtech.system.domain.WorkOrderCategory;
import com.tongtech.system.domain.vo.WorkOrderCategoryTreeSelect;
import com.tongtech.system.mapper.WorkOrderCategoryMapper;
import com.tongtech.system.service.IWorkOrderCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工单类型管理 服务实现
 *
 * @author xingyc
 */
@Service
public class WorkOrderCategoryServiceImpl implements IWorkOrderCategoryService
{
    @Autowired
    private WorkOrderCategoryMapper workOrderCategoryMapper;

    /**
     * 查询工单类型管理数据
     *
     * @param workOrderCategory 工单类型信息
     * @return 工单类型信息集合
     */
    @Override
    @DataScope(deptAlias = "workOrderCategory")
    public List<WorkOrderCategory> selectWorkOrderCategoryList(WorkOrderCategory workOrderCategory)
    {
        return workOrderCategoryMapper.selectWorkOrderCategoryList(workOrderCategory);
    }

    /**
     * 查询工单类型树结构信息
     *
     * @param workOrderCategory 工单类型信息
     * @return 工单类型树信息集合
     */
    @Override
    public List<WorkOrderCategoryTreeSelect> selectWorkOrderCategoryTreeList(WorkOrderCategory workOrderCategory)
    {
        List<WorkOrderCategory> workOrderCategorys = SpringUtils.getAopProxy(this).selectWorkOrderCategoryList(workOrderCategory);
        return buildWorkOrderCategoryTreeSelect(workOrderCategorys);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param workOrderCategorys 工单类型列表
     * @return 树结构列表
     */
    @Override
    public List<WorkOrderCategory> buildWorkOrderCategoryTree(List<WorkOrderCategory> workOrderCategorys)
    {
        List<WorkOrderCategory> returnList = new ArrayList<WorkOrderCategory>();
        List<Long> tempList = workOrderCategorys.stream().map(WorkOrderCategory::getWorkOrderCategoryId).collect(Collectors.toList());
        for (WorkOrderCategory workOrderCategory : workOrderCategorys)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(workOrderCategory.getParentId()))
            {
                recursionFn(workOrderCategorys, workOrderCategory);
                returnList.add(workOrderCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = workOrderCategorys;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param workOrderCategorys 工单类型列表
     * @return 下拉树结构列表
     */
    @Override
    public List<WorkOrderCategoryTreeSelect> buildWorkOrderCategoryTreeSelect(List<WorkOrderCategory> workOrderCategorys)
    {
        List<WorkOrderCategory> deptTrees = buildWorkOrderCategoryTree(workOrderCategorys);
        return deptTrees.stream().map(WorkOrderCategoryTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据工单类型ID查询信息
     *
     * @param workOrderCategoryId 工单类型ID
     * @return 工单类型信息
     */
    @Override
    public WorkOrderCategory selectWorkOrderCategoryById(Long workOrderCategoryId)
    {
        return workOrderCategoryMapper.selectWorkOrderCategoryById(workOrderCategoryId);
    }

    /**
     * 根据ID查询所有子工单类型（正常状态）
     *
     * @param workOrderCategoryId 工单类型ID
     * @return 子工单类型数
     */
    @Override
    public int selectNormalChildrenWorkOrderCategoryById(Long workOrderCategoryId)
    {
        return workOrderCategoryMapper.selectNormalChildrenWorkOrderCategoryById(workOrderCategoryId);
    }

    /**
     * 是否存在子节点
     *
     * @param workOrderCategoryId 工单类型ID
     * @return 结果
     */
    @Override
    public boolean hasChildByWorkOrderCategoryId(Long workOrderCategoryId)
    {
        int result = workOrderCategoryMapper.hasChildByWorkOrderCategoryId(workOrderCategoryId);
        return result > 0;
    }


    /**
     * 校验工单类型名称是否唯一
     *
     * @param workOrderCategory 工单类型信息
     * @return 结果
     */
    @Override
    public boolean checkWorkOrderCategoryNameUnique(WorkOrderCategory workOrderCategory)
    {
        Long deptId = StringUtils.isNull(workOrderCategory.getWorkOrderCategoryId()) ? -1L : workOrderCategory.getWorkOrderCategoryId();
        WorkOrderCategory info = workOrderCategoryMapper.checkWorkOrderCategoryNameUnique(workOrderCategory.getWorkOrderCategoryName(), workOrderCategory.getParentId());
        if (StringUtils.isNotNull(info) && info.getWorkOrderCategoryId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存工单类型信息
     *
     * @param workOrderCategory 工单类型信息
     * @return 结果
     */
    @Override
    public int insertWorkOrderCategory(WorkOrderCategory workOrderCategory)
    {
        WorkOrderCategory info = workOrderCategoryMapper.selectWorkOrderCategoryById(workOrderCategory.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("工单类型停用，不允许新增");
        }
        workOrderCategory.setAncestors(info.getAncestors() + "," + workOrderCategory.getParentId());
        return workOrderCategoryMapper.insertWorkOrderCategory(workOrderCategory);
    }

    /**
     * 修改保存工单类型信息
     *
     * @param workOrderCategory 工单类型信息
     * @return 结果
     */
    @Override
    public int updateWorkOrderCategory(WorkOrderCategory workOrderCategory)
    {
        WorkOrderCategory newParentWorkOrderCategory = workOrderCategoryMapper.selectWorkOrderCategoryById(workOrderCategory.getParentId());
        WorkOrderCategory oldWorkOrderCategory = workOrderCategoryMapper.selectWorkOrderCategoryById(workOrderCategory.getWorkOrderCategoryId());
        if (StringUtils.isNotNull(newParentWorkOrderCategory) && StringUtils.isNotNull(oldWorkOrderCategory))
        {
            String newAncestors = newParentWorkOrderCategory.getAncestors() + "," + newParentWorkOrderCategory.getWorkOrderCategoryId();
            String oldAncestors = oldWorkOrderCategory.getAncestors();
            workOrderCategory.setAncestors(newAncestors);
            updateWorkOrderCategoryChildren(workOrderCategory.getWorkOrderCategoryId(), newAncestors, oldAncestors);
        }
        int result = workOrderCategoryMapper.updateWorkOrderCategory(workOrderCategory);
        if (UserConstants.DEPT_NORMAL.equals(workOrderCategory.getStatus()) && StringUtils.isNotEmpty(workOrderCategory.getAncestors())
                && !StringUtils.equals("0", workOrderCategory.getAncestors()))
        {
            // 如果该工单类型是启用状态，则启用该工单类型的所有上级工单类型
            updateParentWorkOrderCategoryStatusNormal(workOrderCategory);
        }
        return result;
    }

    /**
     * 修改该工单类型的父级工单类型状态
     *
     * @param workOrderCategory 当前工单类型
     */
    private void updateParentWorkOrderCategoryStatusNormal(WorkOrderCategory workOrderCategory)
    {
        String ancestors = workOrderCategory.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        workOrderCategoryMapper.updateWorkOrderCategoryStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param workOrderCategoryId 被修改的工单类型ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateWorkOrderCategoryChildren(Long workOrderCategoryId, String newAncestors, String oldAncestors)
    {
        List<WorkOrderCategory> children = workOrderCategoryMapper.selectChildrenWorkOrderCategoryById(workOrderCategoryId);
        for (WorkOrderCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            workOrderCategoryMapper.updateWorkOrderCategoryChildren(children);
        }
    }

    /**
     * 删除工单类型管理信息
     *
     * @param deptId 工单类型ID
     * @return 结果
     */
    @Override
    public int deleteWorkOrderCategoryById(Long deptId)
    {
        return workOrderCategoryMapper.deleteWorkOrderCategoryById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<WorkOrderCategory> list, WorkOrderCategory t)
    {
        // 得到子节点列表
        List<WorkOrderCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (WorkOrderCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<WorkOrderCategory> getChildList(List<WorkOrderCategory> list, WorkOrderCategory t)
    {
        List<WorkOrderCategory> tlist = new ArrayList<WorkOrderCategory>();
        Iterator<WorkOrderCategory> it = list.iterator();
        while (it.hasNext())
        {
            WorkOrderCategory n = (WorkOrderCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getWorkOrderCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<WorkOrderCategory> list, WorkOrderCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
